import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { ProTable, ActionType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { useModel } from 'umi';
import UploadPkg from './components/UploadPkg';
import { delPkg, queryPackageList } from './service';
import type { PackageTableItem } from './types.d';
import { PackageStatusEnum, PackageTypeEnum } from './types.d';
import { useRef, useState } from 'react';
import UpdatePkg from './components/UpdatePkg';

const PackageList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.packageManager || []) : new Set();
  const ifDelete = auths.has(Auths.DELETE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifCreate = auths.has(Auths.CREATE);
  const [currPkg, setCurrPkg] = useState<PackageTableItem | null>(null);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<PackageTableItem>[] = [
    {
      title: '包名',
      dataIndex: 'pkName',
      align: 'center',
      hideInForm: true,
      renderText: (_, record) => {
        if (currUser?.role == Role.ADMIN) {
          return `${_}(${record.ownerId})`;
        }
        return _;
      },
    },
    {
      title: '版本',
      dataIndex: 'version',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '包类型',
      dataIndex: 'type',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      hideInTable: true,
      valueEnum: {
        [PackageTypeEnum.POS_CHARGE_APK]: { text: '收费POS端APP' },
      },
    },
    {
      title: '包状态',
      dataIndex: 'status',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        [PackageStatusEnum.WAIT]: { text: '待开放', status: 'processing' },
        [PackageStatusEnum.OPEN]: { text: '已开放', status: 'success' },
        [PackageStatusEnum.DEPRECATED]: { text: '已下架', status: 'default' },
      },
    },
    {
      title: '最新版',
      dataIndex: 'isLast',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        false: { text: '否' },
        true: { text: '是' },
      },
    },
    {
      title: '版本说明',
      dataIndex: 'desc',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '下载地址',
      dataIndex: 'url',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => (
        <a href={record.url} download>
          {record.url}
        </a>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      align: 'center',
      render: (_, record, x, action) => {
        if (!ifModify && !ifDelete) return [<PlaceHolderCpn />];
        return [
          ifModify && (
            <a
              onClick={() => {
                setCurrPkg(record);
                setUpdateVisible(true);
              }}
            >
              编辑
            </a>
          ),
          ifDelete && (
            <ConfirmModal
              reload={() => action?.reload()}
              operFunc={async () => await delPkg(record._id)}
              text={`是否确定要删除包「${record.pkName}」 v${record.version}版本`}
            />
          ),
        ];
      },
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '包管理列表',
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/staff',
              breadcrumbName: '员工管理',
            },
            {
              path: '/staff/package-manager',
              breadcrumbName: '包管理',
            },
          ],
        },
      }}
    >
      <ProTable<PackageTableItem>
        style={{ whiteSpace: 'nowrap' }}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        scroll={{
          x: true,
        }}
        actionRef={actionRef}
        rowKey="_id"
        columnEmptyText="暂无数据"
        debounceTime={300}
        request={async (params, sort) => {
          return await queryPackageList(params, sort);
        }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        toolBarRender={(action) => [
          ifCreate && (
            <UploadPkg
              reload={() => {
                action?.reload();
              }}
              isAdmin={currUser?.role == Role.ADMIN}
            />
          ),
        ]}
      />
      {updateVisible && currPkg && (
        <UpdatePkg
          visible={updateVisible}
          currItem={currPkg}
          close={() => {
            setUpdateVisible(false);
            setCurrPkg(null);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
          isAdmin={currUser?.role == Role.ADMIN}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default PackageList;
